<template>

  <el-select
    v-model="currentValue"
    :remote-method="fetchData"
    filterable
    remote
    size="small"
    reserve-keyword
    clearable
    automatic-dropdown
    placeholder="选择或搜索题库"
    class="filter-item"
    @change="handlerChange"
    @clear="fetchData('')"
  >
    <el-option
      v-for="item in dataList"
      :key="item.id"
      :label="item.title"
      :value="item.id"
    />
  </el-select>

</template>

<script>

import { fetchList } from '@/api/repo/repo'

export default {
  name: 'RepoSelect',
  props: {
    value: String,
    forExam: Boolean,
    forTrain: Boolean
  },
  data() {
    return {
      // 下拉选项值
      dataList: [],
      currentValue: ''
    }
  },

  watch: {
    // 检测查询变化
    value: {
      handler() {
        this.fetchData()
      }
    },
    // 检测查询变化
    currentValue: {
      handler(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {

    // 获取数据
    fetchData(e) {
      this.currentValue = this.value

      const query = { current: 1, size: 100, params: { title: e }, useCache: true }
      if (this.forExam) {
        query.params.forExam = true
      }
      if (this.forTrain) {
        query.params.forTrain = true
      }
      fetchList(query).then(res => {
        this.dataList = res.data.records
        this.handlerCode(this.value)
      })
    },
    handlerChange(e) {
      const obj = this.dataList.find((item) => {
        return item.id === e
      })
      if (obj) {
        this.$emit('change', obj)
        this.$emit('code', obj)
      }
      this.$emit('input', e)
    },

    handlerCode(e) {
      if (!e || !this.dataList || this.dataList.length === 0) {
        return
      }
      const obj = this.dataList.find((item) => {
        return item.id === e
      })
      if (obj) {
        this.$emit('code', obj)
      }
    }
  }
}
</script>
